<!-- 仓库设置 -->
<script setup lang="ts">
import type { TreeInstance } from 'element-plus';

import type { VbenFormProps } from '#/adapter/form';
import type {
  OnActionClickParams,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { DictApi, MachineryApi } from '#/api';

import { nextTick, reactive, ref, watch } from 'vue';

import { ColPage, useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { VxeButton } from '@vben/plugins/vxe-table';

import { Button, Tooltip } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteMachinery,
  DictResp,
  getMachineryList,
  getMachineryTypeHandleList,
} from '#/api';
import {
  getToolBarBtns,
  messageError,
  messageSuccess,
  PopMsg,
  setToolBarBtnDefaultDisabled,
  updateToolbarButtonStatus,
} from '#/utils';

import { useColumns, useSearchForm } from './data';
import MachineryForm from './form.vue';

interface Tree {
  [key: string]: any;
}
// 将字典数据添加到数组中
const sys_yes_no = reactive<DictApi.SelectOption[]>([]);

DictResp(['sys_yes_no']).then((res) => {
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});

const buttons = getToolBarBtns();

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: MachineryForm,
  destroyOnClose: true,
});

// 存储选中行的响应式变量
const selectedRows = ref<any[]>([]);

/**
 * 编辑
 * @param row
 */
function onEdit(row: MachineryApi.Row) {
  row.attr1 = '2';
  formModalApi.setData(row).open();
}

/**
 * 查看
 * @param row
 */
function onView(row: MachineryApi.Row) {
  row.attr1 = '1';
  formModalApi.setData(row).open();
}

/**
 * 创建
 */
function onAdd() {
  formModalApi.setData(null).open();
}

/**
 * 删除
 * @param row
 */
function onDelete(row: MachineryApi.Row | MachineryApi.Row[]) {
  const ids = Array.isArray(row)
    ? row.map((item) => item.machineryId)
    : [row.machineryId];
  const idString = ids.join(',');
  PopMsg(
    `确定要删除计划设置编号为【${idString}】的数据吗？`,
    '提示',
    'warn',
  ).then(() => {
    deleteMachinery(idString)
      .then(() => {
        messageSuccess(`删除成功`);
        refreshGrid();
      })
      .catch((error) => {
        messageError(error);
      });
  });
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  wrapperClass: 'grid-cols-2 gap-x-5 gap-y-4',
  schema: useSearchForm(),

  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '搜索',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const gridOptions: VxeGridProps<MachineryApi.Row> = {
  columns: useColumns(onView),
  checkboxConfig: {
    highlight: true,
  },

  scrollbarConfig: {
    x: {
      position: 'bottom',
    },
  },
  // 虚拟滚动配置项
  virtualYConfig: { enabled: true },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    slots: {
      // 自定义分页器
    },
    // 每页显示数量选择
    pageSizes: [5, 10, 20, 50, 100],
    layouts: [
      'Total',
      'Sizes',
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'FullJump',
    ],
    align: 'right',
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getMachineryList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return { items: res.rows, total: res.total };
      },
    },
  },
  tooltipConfig: {
    // 是否开启全局文本提示
    showAll: false,
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    // custom: true,
    // zoom: true,
    refresh: { code: 'query' },
    buttons: buttons.value,
  },
};

const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    switch (code) {
      case 'myAdd': {
        onAdd();
        break;
      }
      case 'myDel': {
        if (selectedRows.value.length > 0) {
          onDelete(selectedRows.value);
        }
        break;
      }
      case 'myEdit': {
        if (selectedRows.value.length === 1) {
          onEdit(selectedRows.value[0] as any);
        } else {
          PopMsg('请选择单行', '提示', 'error');
        }
        break;
      }
      default: {
        break;
      }
    }
    updateToolbarButtonStatus(selectedRows); // 更新按钮状态
  },
  checkboxChange() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    setToolBarBtnDefaultDisabled(buttons, selectedRows.value.length);
  },
  checkboxAll() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    setToolBarBtnDefaultDisabled(buttons, selectedRows.value.length);
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

/**
 * 处理表格操作列点击事件的函数
 *
 * @param {OnActionClickParams<MachineryApi.Row>} - 包含操作代码和行数据的对象
 */
function onActionClick({ code, row }: OnActionClickParams<MachineryApi.Row>) {
  switch (code) {
    case 'myDel': {
      onDelete(row);
      break;
    }
    case 'myEdit': {
      onEdit(row);
      break;
    }
    case 'onView': {
      onView(row);
      break;
    }
    default: {
      break;
    }
  }
  updateToolbarButtonStatus(selectedRows); // 更新按钮状态
}

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}

/* 树形控件 */
const filterText = ref('');
const treeRef = ref<TreeInstance>();

const defaultProps = {
  children: 'children',
  label: 'machineryTypeName',
};
const data = ref<Tree[]>([]);
getMachineryTypeHandleList().then((res) => {
  data.value = res;
  nextTick(() => {
    treeRef.value?.filter('');
  });
});

watch(filterText, (val) => {
  // eslint-disable-next-line unicorn/no-array-callback-reference
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.machineryTypeName.includes(value);
};

function handleNodeClick(data: Tree) {
  gridApi.formApi.getValues().then((res) => {
    res.machineryTypeId = data.machineryTypeId;
    gridApi.query(res);
  });
}

// 双列布局组件属性
const props = reactive({
  leftCollapsedWidth: 5,
  leftCollapsible: true,
  leftMaxWidth: 30,
  leftMinWidth: 15,
  leftWidth: 20,
  resizable: true,
  rightWidth: 90,
  splitHandle: true,
  splitLine: true,
});
</script>

<template>
  <ColPage v-bind="props">
    <!-- <template #title>
      <span class="mr-2 text-2xl font-bold">设备台账</span>
    </template> -->
    <template #left="{ isCollapsed, expand }">
      <div v-if="isCollapsed" @click="expand">
        <Tooltip title="点击展开左侧">
          <Button shape="circle" type="primary">
            <template #icon>
              <IconifyIcon class="text-2xl" icon="bi:arrow-right" />
            </template>
          </Button>
        </Tooltip>
      </div>
      <div
        v-else
        :style="{ minWidth: '200px' }"
        class="border-border bg-card mr-2 rounded-[var(--radius)] border p-2"
      >
        <el-input
          v-model="filterText"
          class="mb-2"
          placeholder="请输入分类名称"
        />
        <el-tree
          ref="treeRef"
          style="height: 100%"
          class="filter-tree"
          :data="data"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
          :expand-on-click-node="false"
          node-key="id"
          highlight-current
        />
      </div>
    </template>
    <FormModal @success="refreshGrid" />
    <Grid class="ml-2">
      <template #action="{ row }">
        <VxeButton
          mode="text"
          icon="vxe-icon-signature"
          @click="onActionClick({ code: 'myEdit', row })"
          status="primary"
        >
          编辑
        </VxeButton>
        <VxeButton
          icon="vxe-icon-delete"
          mode="text"
          @click="onActionClick({ code: 'myDel', row })"
          status="error"
        >
          删除
        </VxeButton>
      </template>
    </Grid>
  </ColPage>
</template>
